package cn.ydt.ydt.sso.webapi.security;

import cn.ydt.ydt.common.resful.StatusCode;
import cn.ydt.ydt.pojo.admin.model.Net;
import cn.ydt.ydt.pojo.admin.vo.NetLoginInfoVO;
import cn.ydt.ydt.pojo.user.vo.UserLoginInfoVO;
import cn.ydt.ydt.sso.webapi.mapper.admin.AdminMapper;
import cn.ydt.ydt.sso.webapi.mapper.user.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String userPhone) throws UsernameNotFoundException {

        //获取用户信息
        UserLoginInfoVO userInfo = userMapper.getUserLoginByPhone(userPhone);

        //获取网格员信息
        Net net = adminMapper.getNetByAccount(userPhone);



        if (userInfo == null && net == null) {
            throw new BadCredentialsException("登录失败，未查询到该账号");
        }



        UserDetails userDetails = null;
        if (userInfo != null){
            userDetails = User.builder()
                    .username(userInfo.getUserPhone())
                    .password(userInfo.getUserPassword())
                    .accountExpired(false)
                    .accountLocked(false)
                    .credentialsExpired(false)
                    .authorities(userInfo.getPermissions().toArray(new String[] {}))
                    .build();
        }else {
            NetLoginInfoVO netInfo = new NetLoginInfoVO();

            BeanUtils.copyProperties(net,netInfo);
            userDetails = User.builder()
                    .username(netInfo.getNetAccount())
                    .password(netInfo.getNetPassword())
                    .accountExpired(false)
                    .accountLocked(false)
                    .credentialsExpired(false)
                    .authorities(netInfo.getPermissions().toArray(new String[] {}))
                    .build();
        }


        System.out.println("转换得到UserDetails=" + userDetails);
        return userDetails;
    }

}
